package com.siss.tenancy.user.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Json消息转换
 * 解决null、日期格式json的处理
 *
 * @author yingw
 * @version 1.0
 */
@Configuration
public class Json2HttpMessageConverter {

    @Bean
    public MappingJackson2HttpMessageConverter jsonConverter() {

        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper objectMapper = new ObjectMapper();

        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);

        DefaultSerializerProvider defaultSerializerProvider = new DefaultSerializerProvider.Impl();

        JsonSerializer<Object> nullJsonSerializer = new JsonNullValueSerializer();
        defaultSerializerProvider.setNullValueSerializer(nullJsonSerializer); // 序列化null值自定义处理
        objectMapper.setSerializerProvider(defaultSerializerProvider);

        //日期转换Json  但是当数据库字段为date类型时，@ResponseBody注解在转换日期类型时会默认把日期转换为时间戳（例如： date：2017-10-25  转换为 时间戳：15003323990）
        SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //"yyyy-MM-dd"
        objectMapper.setDateFormat(smt);

        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);

        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);

        return mappingJackson2HttpMessageConverter;
    }

}

class JsonNullValueSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
            throws IOException, JsonProcessingException {

        JsonStreamContext outputContext = gen.getOutputContext();
        String currentName = outputContext.getCurrentName();
        Object currentValue = outputContext.getCurrentValue();
        Class<? extends Object> class1 = currentValue.getClass();
        try {
            Field declaredField = class1.getDeclaredField(currentName);
            Class<?> type = declaredField.getType();
            if (type == Integer.class) { // Integer类型null值处理为0
                gen.writeNumber(0);
                return;
            }
        } catch (NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
        }

        gen.writeString(""); // 其他null值缺省处理为空""

    }
}